import pytest
import yaml

from common import common_func
from common.common_read_file import CommonReadFile
from common.common_requests import CommonHttp
from common.common_func import get_env

@pytest.fixture(scope='function', name='http')
def common_http(get_config):
    print(get_config['base_url'])
    common = CommonHttp(get_config['base_url'])
    yield common


'''
如果改成module，每个测试文件都会执行一次，那每个文件获取的token不一样
如果改成function，每个方法都会执行一次，那每个方法获取的token也不一样
'''


# 获取token
@pytest.fixture(scope='session', name='token')
def access_token(get_config):
    common = CommonHttp(get_config['base_url'])
    APPID = get_config['appid']  # 'wx20d87c72dc1e93bf'
    APPSECRET = get_config['appsecret']  # 'deeced62d97f6ec9a53db64dd5dd1bf0'
    token_url = '/token?grant_type=client_credential&appid=%s&secret=%s' % (APPID, APPSECRET)
    response_token = common.get(token_url)
    print('http状态码=%s, response.json=%s ' % (response_token.status_code, response_token.json()))
    # print('token=%s' % response_token.json()['access_token'])
    token = response_token.json()['access_token']
    assert response_token.status_code == 200
    yield token


@pytest.fixture(scope='session', name='token')
def access_token1():
    token = '62_Q5Th9XGfmsSmRM8RcHIr38ypIbAZEQLU7EoNXFjZ3AcQCwSF9bDW-5uabojBWrOHQM4fPhLKpsK3X5EbQB_QXG3Ng8kGcBuZFW10i4dlsXve0gMa13CaGxxwO4oWneKh7Vq6aBMgmXfw1dMnYWSiABABZV'
    yield token

'''
def pytest_addoption(parser):
    # 注册自定义参数env到配置对象
    parser.addoption(
        "--env", action="store", choices=['test', 'pre', 'prd'], help="test:测试环境, pre:预发环境, prd:生产环境"
    )
'''

@pytest.fixture(scope='session', name='get_config')
def get_config(get_env, log_start_end):
    with open('config.yaml', encoding="utf-8") as f:
        dict_data = yaml.safe_load(f.read())
        data = dict_data[get_env]
        print(dict_data[get_env])
    yield data

'''
@pytest.fixture(scope='session', name='get_env')
def get_env(request):
    get_env
    # 从配置对象获取env的值
    env = request.config.getoption("--env")
    yield env
'''
@pytest.fixture(scope="session")
def get_env():
    return common_func.get_env()


@pytest.fixture(scope='session', name='log_start_end')
def log_start_end(get_env):
    print('当前%s环境，测试开始' % get_env)
    #yield get_env
    print('当前%s环境，测试用例执行完成，测试结束！' % get_env)
